package com.atguigu.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.dao.AdminRoleDao;
import com.atguigu.dao.BaseDao;
import com.atguigu.dao.RoleDao;

import com.atguigu.entity.AdminRole;
import com.atguigu.entity.Role;

import com.atguigu.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service(interfaceClass = RoleService.class)
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private AdminRoleDao adminRoleDao;


    @Override
    protected BaseDao<Role> getEntityDao() {
        return roleDao;
    }

    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public Map<String, Object> findRoleByAdminId(Long adminId) {
        // 获取所有角色
        List<Role> roleList = roleDao.findAll();
        // 获取用户已拥有的角色的角色id
        List<Long> roleIds = adminRoleDao.findRolesByAdminId(adminId);
        // 判断已选择和未选择的权限
        List<Role> noAssignRoleList = new ArrayList<>(); // 未选中
        List<Role> assignRoleList = new ArrayList<>(); // 已选中
        // 遍历角色
        for (Role role : roleList) {
            // 判断当前角色在不在roleIds中
            if (roleIds.contains(role.getId())){
                assignRoleList.add(role);
            }else {
                noAssignRoleList.add(role);
            }
        }
        // 创建返回的Map
        Map<String,Object> roleMap = new HashMap<>();
        roleMap.put("noAssignRoleList" , noAssignRoleList);
        roleMap.put("assignRoleList" , assignRoleList);
        return roleMap;
    }

    @Override
    public void assignRole(Long adminId, Long[] roleIds) {
        // 根据用户ID将已分配角色删除
        adminRoleDao.deleteRoleByAdminId(adminId);

        // 遍历所有角色id
        for(Long roleId : roleIds) {
            // 前端传入的数据是1,3,5, 则需要处理最后一个逗号，所以需要判空
            if(StringUtils.isEmpty(roleId)) continue;
            // 将用户id 角色id插入到数据库中
            AdminRole userRole = new AdminRole();
            userRole.setAdminId(adminId);
            userRole.setRoleId(roleId);
            adminRoleDao.insert(userRole);
        }
    }
}
